package com.medical.data.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.medical.data.component.LoginUserThreadLocal;
import com.medical.data.constEnum.CommonEnum;
import com.medical.data.domain.Patient;
import com.medical.data.domain.ProjectData;
import com.medical.data.domain.User;
import com.medical.data.domain.UserProject;
import com.medical.data.exception.MyException;
import com.medical.data.mapper.ProjectDataMapper;
import com.medical.data.service.ProjectDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.medical.data.service.TokenSerivce;
import com.medical.data.service.UserPermissionService;
import com.medical.data.service.UserProjectService;
import com.medical.data.utils.DateUtil;
import com.medical.data.utils.ResultCode;
import com.medical.data.vo.FormResultVo;
import com.medical.data.vo.GetProjectVo;
import com.medical.data.vo.ProjectResultVo;
import com.medical.data.vo.ProjectVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author cj
 * @since 2024-02-06
 */
@Service
@Slf4j
public class ProjectDataServiceImpl extends ServiceImpl<ProjectDataMapper, ProjectData> implements ProjectDataService {

    @Autowired
    private TokenSerivce tokenSerivce;

    @Autowired
    private UserProjectService userProjectService;

    @Autowired
    private UserPermissionService userPermissionService;

    @Override
    public void createProject(ProjectVo projectVo) {
        User user = tokenSerivce.getUser();
        /*projectVo.setUserId(user.getId());*/
        //查询该项目是否已存在,多表查询
        projectVo.setUserId(user.getId());
        Integer integer = baseMapper.getProjectByUserId(projectVo);
        if (integer != 0) {
            throw new MyException(ResultCode.ERROR.getCode(), "该项目已存在请重新输入");
        }
        ProjectData projectData = new ProjectData();
        //项目不存在
        BeanUtils.copyProperties(projectVo, projectData);
        projectData.setUserId(user.getId());
        int insert = baseMapper.insert(projectData);
        if (insert < 1)
            throw new MyException(ResultCode.ERROR.getCode(), "新增项目失败");
        //新增成功以后需要对中间表进行更新
        UserProject userProject = new UserProject();
        userProject.setProjectId(projectData.getId());
        userProject.setUserId(user.getId());
        boolean save = userProjectService.save(userProject);
        if (!save) {
            throw new MyException(ResultCode.ERROR.getCode(), "新增项目失败");
        }
        //在用户权限表中给予创建者最高权限
        userPermissionService.createOwnUser(user.getId(), projectData.getId());
    }

    @Override
    public IPage<ProjectVo> getProjectById(int currentPage, int pageSize) {

        User user = LoginUserThreadLocal.get().getUser();
        if (ObjectUtils.isEmpty(user)) {
            throw new MyException(ResultCode.ERROR.getCode(), "用户不存在");
        }

        // 构建分页对象
        Page<ProjectData> page = new Page<>(currentPage, pageSize);

        LambdaQueryWrapper<ProjectData> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProjectData::getUserId, user.getId());

        // 执行分页查询
        IPage<ProjectData> projectDataPage = baseMapper.selectPage(page, wrapper);

        // 将查询结果转换为VO对象
        List<ProjectVo> projectVoList = new ArrayList<>();
        for (ProjectData projectData : page.getRecords()) {
            ProjectVo projectVo = new ProjectVo();
            BeanUtils.copyProperties(projectData, projectVo);
            projectVoList.add(projectVo);
        }

        // 创建新的分页结果对象，设置转换后的记录列表和总记录数
        IPage<ProjectVo> resultPage = new Page<>(currentPage, pageSize, projectDataPage.getTotal());
        resultPage.setRecords(projectVoList);

        // 返回分页结果
        return resultPage;
    }

    @Override
    public Map<String, Object> getProjectByUser(GetProjectVo getProjectVo) {
        User user = tokenSerivce.getUser();
        Integer currentPage = CommonEnum.CURRENT.getValue();
        Integer pageSize = CommonEnum.LIMIT1.getValue();
        LambdaQueryWrapper<ProjectData> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProjectData::getUserId, user.getId());
        //做分页
        if (!org.apache.commons.lang3.ObjectUtils.isEmpty(getProjectVo.getCurrentPage())) {
            currentPage = getProjectVo.getCurrentPage();
        }
        if (!org.apache.commons.lang3.ObjectUtils.isEmpty(getProjectVo.getPageSize())) {
            pageSize = getProjectVo.getPageSize();
        }
        if (!StringUtils.isEmpty(getProjectVo.getName())) {
            wrapper.like(ProjectData::getName, getProjectVo.getName());
        }
        wrapper.orderByDesc(ProjectData::getCreateTime);//降序排序

        Page<ProjectData> page = new Page<>(currentPage, pageSize);
        baseMapper.selectPage(page, wrapper);
        List<ProjectData> projectData = page.getRecords();
        for(String projectId:userPermissionService.getProjectByUserId(user.getId())){
            LambdaQueryWrapper<ProjectData>wrapper1=new LambdaQueryWrapper<>();
            wrapper1.eq(ProjectData::getId,projectId);
            System.out.println(projectId);
            ProjectData projectData1 =this.baseMapper.selectOne(wrapper1);
            projectData.add(projectData1);
        }
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("total", page.getTotal());
        map.put("current", page.getCurrent());
        map.put("patientVos", projectData);
        return map;
    }

    @Override
    public ProjectData getProjectDataById(String projectId) {
        return baseMapper.selectOne(Wrappers.<ProjectData>lambdaQuery().eq(ProjectData::getId, projectId));
    }

    @Override
    public void updateProject(ProjectVo projectVo, String projectId) {
        ProjectData projectData = new ProjectData();
        BeanUtils.copyProperties(projectVo, projectData);
        projectData.setId(projectId);
        baseMapper.updateById(projectData);
    }

    @Override
    public void deleteProjectById(String projectId) {
        //先删除项目表
        int delete = baseMapper.delete(Wrappers.<ProjectData>lambdaQuery().eq(ProjectData::getId, projectId));
        if (delete < 1) {
            throw new MyException(ResultCode.ERROR.getCode(), "删除项目失败");
        }
        //在删除用户项目中间表
        userProjectService.deleteProjectById(projectId);
        if (delete < 1) {
            throw new MyException(ResultCode.ERROR.getCode(), "删除患者节点表数据失败");
        }
        //删除共享用户中的数据
        userPermissionService.deleteUserByProjectId(projectId);
    }

    @Override
    public void updatePatientNumber(String project) {
        //更新项目表中的病例数量
        //首先查询项目
        ProjectData projectData = baseMapper.selectById(project);
        if (ObjectUtils.isEmpty(projectData)) {
            throw new MyException(ResultCode.ERROR.getCode(), "项目不存在");
        }
        if (projectData.getPatientNumber() == null)
            projectData.setPatientNumber(0);
        LambdaUpdateWrapper<ProjectData> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(ProjectData::getId, projectData.getId());
        lambdaUpdateWrapper.set(ProjectData::getPatientNumber, projectData.getPatientNumber() + 1);
        int update = this.baseMapper.update(null, lambdaUpdateWrapper);
        if (update < 1) {
            throw new MyException(ResultCode.ERROR.getCode(), "更新病例数量失败");
        }
    }

    @Override
    public int getProjectNumber() {
        User user = tokenSerivce.getUser();
        LambdaQueryWrapper<ProjectData> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProjectData::getUserId, user.getId());
        List<ProjectData> projectData = this.baseMapper.selectList(wrapper);
        return projectData.size();
    }

    @Override
    public int getTodayProjectNumber() {
        User user = tokenSerivce.getUser();
        LocalDate today = LocalDate.now();

        LambdaQueryWrapper<ProjectData> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProjectData::getUserId, user.getId())
                .apply("DATE(create_time) = DATE({0})", today); // 使用DATE()函数比较日期部分

        List<ProjectData> projectData = this.baseMapper.selectList(wrapper);
        return projectData.size();
    }

    @Override
    public void projectValid(String projectId) {
        LambdaQueryWrapper<ProjectData> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProjectData::getId, projectId);
        ProjectData projectData = this.baseMapper.selectOne(wrapper);
        if (ObjectUtils.isEmpty(projectData)) {
            throw new MyException(ResultCode.ERROR.getCode(), "项目不存在");
        }
        Date endTime = projectData.getEndTime();
        if (DateUtil.compareDateAndTime(new Date(), endTime)) {
            throw new MyException(ResultCode.ERROR.getCode(), "项目已结束");
        }
    }

    @Override
    public Map<String, Object> getShareProject(GetProjectVo getProjectVo) {
        User user = tokenSerivce.getUser();
        Integer currentPage = CommonEnum.CURRENT.getValue();
        Integer pageSize = CommonEnum.LIMIT1.getValue();
        LambdaQueryWrapper<ProjectData> wrapper = new LambdaQueryWrapper<>();
        //做分页
        if (!org.apache.commons.lang3.ObjectUtils.isEmpty(getProjectVo.getCurrentPage())) {
            currentPage = getProjectVo.getCurrentPage();
        }
        if (!org.apache.commons.lang3.ObjectUtils.isEmpty(getProjectVo.getPageSize())) {
            pageSize = getProjectVo.getPageSize();
        }
        if (!StringUtils.isEmpty(getProjectVo.getName())) {
            wrapper.like(ProjectData::getName, getProjectVo.getName());
        }
        wrapper.ne(ProjectData::getUserId, user.getId());//找到非自己创建的可共享项目,加入别人的项目
        wrapper.eq(ProjectData::getIsShare, true);
        wrapper.orderByDesc(ProjectData::getCreateTime);//降序排序

        Page<ProjectData> page = new Page<>(currentPage, pageSize);
        baseMapper.selectPage(page, wrapper);
        List<ProjectData> projectData = page.getRecords();
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("total", page.getTotal());
        map.put("current", page.getCurrent());
        map.put("patientVos", projectData);
        return map;
    }

    @Override
    public List<FormResultVo> getProjects() {
        List<FormResultVo> list = new ArrayList<>();
        User user = tokenSerivce.getUser();
        LambdaQueryWrapper<ProjectData> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProjectData::getUserId, user.getId());
        List<ProjectData> projectData = this.baseMapper.selectList(wrapper);
        for (ProjectData project : projectData) {
            if (userPermissionService.checkRealUser(user.getId(), project.getId())) {
                FormResultVo formResultVo = new FormResultVo();
                formResultVo.setId(project.getId());
                formResultVo.setName(project.getName());
                list.add(formResultVo);
            }
        }
        return list;
    }
}
